<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Todo List</title>
    <link rel="stylesheet" href="assets/css/base.css">
    <link rel="stylesheet" href="assets/css/index.css">
    <link rel="stylesheet" href="/js/nprogress/nprogress.css">
</head>

<body>
    <section class="todoapp">
        <header class="header">
            <h1>todos</h1>
            <input type="text" class="new-todo" placeholder="What needs to be done?" autofocus id="task">
        </header>
        <!-- This section should be hidden by default and shown when there are todos -->
        <section class="main">
            <input class="toggle-all" type="checkbox">
            <ul class="todo-list" id="todo-list"></ul>
        </section>
        <!-- This footer should hidden by default and shown when there are todos -->
        <footer class="footer">
            <!-- This should be `0 items left` by default -->
            <span class="todo-count"><strong id="count">0</strong> item left</span>
            <!-- Remove this if you don't implement routing -->
            <ul class="filters">
                <li>
                    <a class="selected" href="javascript:;" id="all">All</a>
                </li>
                <li>
                    <a href="javascript:;" id="active">Active</a>
                </li>
                <li>
                    <a href="javascript:;" id="complete">Completed</a>
                </li>
            </ul>
            <!-- Hidden if no completed items are left ↓ -->
            <button class="clear-completed">Clear completed</button>
        </footer>
    </section>
    <script src="/js/jquery.min.js"></script>
    <script src="/js/template-web.js"></script>
    <script src="/js/nprogress/nprogress.js"></script>
    <!-- 创建模板 -->
    <script type="text/html" id='taskTpl'>
        {{each tasks}}
        <li class="{{$value.completed ? 'completed' : ''}}">
            <div class="view">
                <input class="toggle" type="checkbox" {{$value.completed ? 'checked' : ''}}>
                <label>{{$value.title}}</label>
                <button class="destroy" data-id="{{$value._id}}"></button>
            </div>
            <input class="edit">
        </li>
        {{/each}}
    </script>
    <script>
        // 声明变量，将数据放在任务数组中
        var taskAry = [];
        // 获取容器对象
        var listBox = $('#todo-list');
        // 获取输入框对象
        var taskInp = $('#task');
        // 获取未完成数量
        var strong = $('#count');
        // 获取all, active, completed,clear-completed
        var all = $('#all');
        var active = $('#active');
        var complete = $('#complete');
        var clearCompleted = $('.clear-completed');

        // 全局事件 ajaxStart() 当发送ajax请求时触发， 绑定在document中
        $(document).on('ajaxStart', function() {
            NProgress.start();
        });
        // 全局事件 ajaxComplete() 当完成ajax请求时触发， 绑定在document中
        $(document).on('ajaxComplete', function() {
            NProgress.done();
        });


        // 发送ajax请求，获取数据
        $.ajax({
            type: 'get',
            url: '/todo/task',
            success: function(response) {
                // console.log(response);
                taskAry = response;
                // 将模板与数据结合
                templateTask();
                // 计算未完成任务数量
                calcCount();
            }
        });

        // 为输入添加键盘抬起事件
        taskInp.on('keyup', function(event) {
            // 判断用户是否按下回车按钮
            if (event.keyCode == 13) {
                // 判断用户输入是否为空
                var taskName = $(this).val();
                // 如果用书输入内容为空，提示并阻止代码向下执行
                if (taskName.trim().length == 0) {
                    alert('请输入内容');
                    return;
                }
                $.ajax({
                    type: 'post',
                    url: '/todo/addTask',
                    contentType: 'application/json',
                    dataType: 'json',
                    data: JSON.stringify({
                        title: taskName
                    }),
                    success: function(response) {
                        // console.log(response);
                        taskAry.push(response);
                        templateTask();
                        taskInp.val('');
                        // 计算未完成任务数量
                        calcCount();
                    }
                });
            }
        });
        // 封装模板
        function templateTask() {
            var html = template('taskTpl', {
                tasks: taskAry
            });
            listBox.html(html);
        }

        // 为ul添加点击事件，删除li 委托事件
        listBox.on('click', '.destroy', function() {
            // 获取li的id
            var id = $(this).attr('data-id');
            // 发送请求
            $.ajax({
                type: 'get',
                url: '/todo/deleteTask',
                data: {
                    _id: id
                },
                success: function(response) {
                    var id = taskAry.findIndex(item => item._id == id);
                    taskAry.splice(id, 1);
                    templateTask();
                    // 计算未完成任务数量
                    calcCount();
                }
            });
        });

        // 为复选框添加onchange事件
        listBox.on('change', '.toggle', function() {
            // 获取复选框是否选中状态
            var status = $(this).is(':checked');
            // console.log(status);
            // 或取当前复选框对应的id
            var id = $(this).siblings('button').attr('data-id');
            // console.log(id);
            // 发送ajax请求
            $.ajax({
                type: 'post',
                url: '/todo/modifyTask',
                data: JSON.stringify({
                    _id: id,
                    completed: status
                }),
                contentType: 'application/json',
                success: function(response) {
                    // console.log(response);
                    // 更新状态
                    var task = taskAry.find(item => item._id == id);
                    task.completed = response.completed;
                    // 渲染
                    templateTask();
                    // 计算未完成任务数量
                    calcCount();
                }
            });
        });

        // 为label标签添加双击事件
        listBox.on('dblclick', 'label', function() {
            // 让任务名称处于编辑状态
            $(this).parent().parent().addClass('editing');
            // window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
            // 将任务名称显示在文本框中
            $(this).parent().siblings('input').val($(this).text());
            // 让文本框自动获取焦点
            $(this).parent().siblings('input').focus();
        });

        // 当文本框离开焦点
        listBox.on('blur', '.edit', function() {
            // 获取最新任务名称
            var newTaskName = $(this).val();
            // 编辑任务id
            var id = $(this).siblings().find('button').attr('data-id');
            // 向服务器端发送请求
            $.ajax({
                type: 'post',
                url: '/todo/modifyTask',
                data: JSON.stringify({
                    _id: id,
                    title: newTaskName
                }),
                contentType: 'application/json',
                success: function(response) {
                    // console.log(response);
                    // 同步任务状态
                    var task = taskAry.find(item => item._id == id);
                    task.title = response.title;
                    templateTask();
                    // 计算未完成任务数量
                    calcCount();
                }
            });
        });
        // 封装用于计算为完成任务的数量
        function calcCount() {
            // 存储未完成变量
            var count = 0;
            // 将未完成的任务过滤到一个新的数组中
            var newAry = taskAry.filter(item => item.completed == false);
            // 将新数组的任务数量长度赋值给count
            count = newAry.length;
            // 将未完成的任务数量显示在页面中
            strong.text(count);
        }

        // 点击all事件
        all.on('click', function() {
            $.ajax({
                type: 'get',
                url: '/todo/task',
                success: function(response) {
                    taskAry = response;
                    templateTask();
                    // $(this).addClass('selected').parent().siblings().children().removeClass('selected');
                }
            })
            $(this).addClass('selected').parent().siblings().children().removeClass('selected');

        });
        // 点击active事件
        active.on('click', function() {
            var activeAry = taskAry.filter(item => item.completed == false);
            var html = template('taskTpl', {
                tasks: activeAry
            });
            listBox.html(html);
            // taskAry = activeAry;
            // templateTask();
            $(this).addClass('selected').parent().siblings().children().removeClass('selected');
        });
        // 点击complete事件
        complete.on('click', function() {
            var completeAry = taskAry.filter(item => item.completed == true);
            var html = template('taskTpl', {
                tasks: completeAry
            });
            listBox.html(html);
            // taskAry = completeAry;
            // templateTask();
            $(this).addClass('selected').parent().siblings().children().removeClass('selected');

        });

        // 点击clearCompleted事件
        clearCompleted.on('click', function() {
            $.ajax({
                type: 'get',
                url: '/todo/clearTask',
                success: function(response) {
                    taskAry = response;
                    templateTask();
                }
            });
        });
    </script>
</body>

</html>